import pytest
from playwright.sync_api import sync_playwright
import os
from dotenv import load_dotenv
import allure

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '.env'))


@pytest.fixture(scope='function')
def driver(request):
    browser_type = os.getenv('BROWSER').lower()
    with sync_playwright() as p:
        # 根据配置选择浏览器
        if browser_type == 'chrome':
            browser = p.chromium.launch(headless=False)  # headless=False显示浏览器
        elif browser_type == 'firefox':
            browser = p.firefox.launch(headless=False)
        else:
            raise ValueError(f"不支持的浏览器类型: {browser_type}")

        page = browser.new_page()  # Playwright用page代替driver
        # 设置浏览器窗口尺寸大小
        page.set_viewport_size({"width":1680, "height":900})
        page.set_default_timeout(int(os.getenv('TIMEOUT', '10')) * 1000)  # 超时时间（毫秒）
        yield page
        browser.close()  # 关闭浏览器


# 保留Allure截图钩子（适配Playwright）
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        page = item.funcargs.get('driver', None)  # 这里的driver实际是playwright的page
        if page:
            try:
                screenshot = page.screenshot()  # Playwright截图方法
                allure.attach(screenshot, name="失败截图", attachment_type=allure.attachment_type.PNG)
            except Exception as e:
                print(f"截图失败: {str(e)}")